package org.ishequ.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class AddNewsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("name");
		String timelen = req.getParameter("timelen");
		System.out.println("名称:"+name);
		System.out.println("时长:"+timelen);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if(isMultipart){
			FileItemFactory fileItemFactory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> fileItems = upload.parseRequest(req);
				String dir = req.getSession().getServletContext().getRealPath("/files");
				File dirfile = new File(dir);
				if(!dirfile.exists()) dirfile.mkdir();
				for(FileItem item:fileItems){
					if(item.isFormField()){ //文本类型的表单数据
						String name = item.getFieldName();
						String value = item.getString("UTF-8");
						System.out.println(name+ "="+ value);
					}else{
						System.out.println(dir);
						File savefile = new File(dirfile,item.getName());
						item.write(savefile);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			doGet(req, resp);
		}
	}
}
